package com.sloan.community.config;

import com.sloan.community.po.BasePO;
import com.sloan.community.po.User;
import com.sloan.community.util.SnowflakeIdGenerator;
import lombok.Setter;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.r2dbc.mapping.event.BeforeConvertCallback;
import org.springframework.data.relational.core.sql.SqlIdentifier;
import org.springframework.stereotype.Component;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.Objects;

import static com.sloan.community.common.Constant.SESSION_USER;

/**
 * BeforeSaveCallback 和 BeforeConvertCallback 差不多效果一样
 */
@Component
public class DefaultBeforeConvertCallBack implements BeforeConvertCallback<BasePO>{

    @Autowired
    private SnowflakeIdGenerator generator;

    @Setter
    private WebSession session;

    @Override
    public Publisher<BasePO> onBeforeConvert(BasePO entity, SqlIdentifier table) {
        User user = session.getAttribute(SESSION_USER);

        if (Objects.isNull(entity.getId())) {
            entity.setId(generator.nextId());
            if (Objects.nonNull(user)) {
                entity.setCreatedBy(user.getId());
            } else {
                entity.setCreatedBy(0L);
            }
            entity.setCreatedTime(LocalDateTime.now());

        } else {

            if (Objects.nonNull(user)) {
                entity.setUpdatedBy(user.getId());
            } else {
                entity.setUpdatedBy(0L);
            }
            entity.setUpdatedTime(LocalDateTime.now());

        }
        return Mono.just(entity);
    }


}
